//
//  MusicPlayViewController.m
//  CarOfHome2
//
//  Created by 杨建家－52 on 15/9/24.
//  Copyright © 2015年 Frank. All rights reserved.
//

#import "MusicPlayViewController.h"
#import "HTTPTool.h"
#import "MusicSongFormCell.h"
#import "NetworkHandle.h"

@interface MusicPlayViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) MusicView *musicView;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) AVPlayer *song;
@property (nonatomic, strong) NSMutableArray *songList;
@property (nonatomic, strong) NSMutableArray *picList;
@property (nonatomic, strong) NSMutableArray *singerNameList;
@property (nonatomic, strong) NSMutableArray *songNameList;
@property (nonatomic, strong) NSMutableArray *singerIdList;
@property (nonatomic, strong) NSMutableArray *songIdList;
@property (nonatomic, assign) NSInteger i;
@property (nonatomic, strong) NSMutableArray *valueArr;
@property (nonatomic, copy) NSString *url;
@property (nonatomic,assign) NSInteger n;
@property (nonatomic,strong) MusicModel *valueMusic;
@property (nonatomic ,strong) AVPlayerItem *playerItem;
@property (nonatomic,assign) CGFloat videoDuration;
@property (nonatomic,assign) int currentTimeSec;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIView *songForm;
@property (nonatomic,strong) UIButton *list;
@property (nonatomic,copy) NSString *picUrl;


@end

@implementation MusicPlayViewController
- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    // Do any additional setup after loading the view.
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.list = [UIButton buttonWithType:UIButtonTypeCustom];
    self.list.frame = CGRectMake(20 * SAWindth, 570 * SAHeight, 50 * SAWindth, 50 * SAHeight);
    [self.list setImage:[UIImage imageNamed:@"gedan.png"] forState:UIControlStateNormal];
    [self.list addTarget:self action:@selector(songForm:) forControlEvents:UIControlEventTouchUpInside];
    self.songForm = [[UIView alloc]initWithFrame:CGRectMake(125 * SAWindth, 80 * SAHeight, 250 * SAWindth, 400 * SAHeight)];
    [self.songForm setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"viewbg1.jpg"]]];
   
  //  self.songForm.backgroundColor = [UIColor colorWithRed:5 green:5 blue:5 alpha:0];
    self.songForm.hidden = YES;
    [self dataHandle];
    [self tableViewSubView];
    [self musicViewSubViews];
}
- (void)dataHandle{
    self.songList = [NSMutableArray array];
    self.picList = [NSMutableArray array];
    self.singerNameList = [NSMutableArray array];
    self.songNameList = [NSMutableArray array];
    self.singerIdList = [NSMutableArray array];
    self.songIdList = [NSMutableArray array];
    self.valueArr = [NSMutableArray array];
    NSMutableArray *temp = [NSMutableArray array];
    self.valueArr = self.block(temp);
    NSLog(@"%@",self.valueArr);
    for (MusicModel *model in [self.valueArr firstObject]) {
        
        NSString *url = model.url;
        NSString *singerName = model.singerName;
        NSString *songName = model.name;
        NSString *songId = model.songId;
        NSString *singerId = model.singerId;
        [self.songIdList addObject:songId];
        [self.singerIdList addObject:singerId];
        [self.songList addObject:url];
        [self.singerNameList addObject:singerName];
        [self.songNameList addObject:songName];
    }
    self.i =[[self.valueArr lastObject] integerValue];
    
}
- (void)musicViewSubViews{
   
    self.count = 0;

    self.musicView = [[MusicView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:self.musicView];
    [self.musicView addSubview:self.list];
    [self.musicView addSubview:self.songForm];

    [self.musicView.back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    [self.musicView.like addTarget:self action:@selector(like:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.musicView.play addTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.musicView.last addTarget:self action:@selector(last:) forControlEvents:UIControlEventTouchUpInside];
    [self.musicView.backList addTarget:self action:@selector(backList:) forControlEvents:UIControlEventTouchUpInside];
    [self.musicView.next addTarget:self action:@selector(next:) forControlEvents:UIControlEventTouchUpInside];

    
    self.musicView.songName.text = self.songNameList[self.i];
    self.musicView.singer.text = self.singerNameList[self.i];
    NSString *ut = @"VgIbFN80Es0DAHYc%2F%2BDqHZTA";
    NSString *str = self.singerNameList[self.i];
    NSString *name = [str stringByReplacingOccurrencesOfString:@" " withString:@"+"];
    NSString *singname = [name stringByReplacingOccurrencesOfString:@";" withString:@"%3b"];
    NSLog(@"%@",singname);
    NSString *url = [NSString stringWithFormat:@"http://so.ard.iyyin.com/s/pic?singerid=%@&utdid=%@&song_id=%@&artist=%@&y=1280&x=720",self.singerIdList[self.i],ut,self.songIdList[self.i],singname];
    NSLog(@"%@",url);
    [NetworkHandle GETWithURL:url complication:^(id result) {
        NSDictionary *dic = result;
        NSLog(@"12412");
        NSMutableArray *arr = [dic objectForKey:@"data"];
        if (arr.count == 0) {
            self.picUrl = @"";
            [self.musicView.background sd_setImageWithURL:[NSURL URLWithString:self.picUrl] placeholderImage:[UIImage imageNamed:@"bg.jpg"]];
            [self.musicView.photo sd_setImageWithURL:[NSURL URLWithString:self.picUrl] placeholderImage:[UIImage imageNamed:@"bg.jpg"]];
        }
        else{
            self.picUrl = [[[[arr firstObject]objectForKey:@"picUrls"]firstObject]objectForKey:@"picUrl"];
            [self.musicView.background sd_setImageWithURL:[NSURL URLWithString:self.picUrl] placeholderImage:[UIImage imageNamed:@"bg.jpg"]];
            [self.musicView.photo sd_setImageWithURL:[NSURL URLWithString:self.picUrl] placeholderImage:[UIImage imageNamed:@"bg.jpg"]];
            NSLog(@"%@",self.picUrl);
        }
 
        
        
    }];
    
    NSURL *songUrl = [NSURL URLWithString:self.songList[self.i]];
    self.playerItem = [AVPlayerItem playerItemWithURL:songUrl];
    [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];// 监听status属性
    self.song = [AVPlayer playerWithPlayerItem:self.playerItem];
    
    [self.musicView.plan addTarget:self action:@selector(planDrag) forControlEvents:UIControlEventValueChanged];
    [self.musicView.volume addTarget:self action:@selector(volume:) forControlEvents:UIControlEventValueChanged];
    
    
    self.musicView.leftTime.text = @"0:00";
    self.musicView.rightTime.text = @"0:00";
    
    UISwipeGestureRecognizer *swip2 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swip2:)];
    [self.musicView addGestureRecognizer:swip2];
    swip2.direction = UISwipeGestureRecognizerDirectionLeft;
    self.musicView.play.enabled = NO;
    
}
- (void)backList : (UIButton *)button{

    self.songForm.hidden = YES;
    
}
- (void)tableViewSubView{
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.songForm.frame.size.width, self.songForm.frame.size.height) style:UITableViewStylePlain];
    [self.songForm addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor colorWithRed:251/255.0f green:247/255.0f blue:237/255.0f alpha:0];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    MusicSongFormCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (cell == nil) {
        cell = [[MusicSongFormCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"];
    }
    cell.backgroundColor = [UIColor colorWithRed:5 green:5 blue:5 alpha:0];
    MusicModel *musicModel = [[MusicModel alloc]init];
    musicModel = [self.valueArr firstObject][indexPath.row];
    cell.musicModel = musicModel;
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.song pause];
    [self.playerItem removeObserver:self forKeyPath:@"status"];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
    [self.timer invalidate];
    self.timer = nil;
    self.n = 0;
    self.i = indexPath.row;
    
    [self musicViewSubViews];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"%lu",(unsigned long)self.valueArr.count);
    return [[self.valueArr firstObject]count];
    
}
- (void)songForm : (UIButton *)button{
    if (self.songForm.hidden == 1) {
        self.songForm.hidden = NO;
    }
    else {
        self.songForm.hidden = YES;
    }
}

- (void)volume : (UISlider *)slider{
    
    
    self.song.volume =self.musicView.volume.value;
    
    
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                        change:(NSDictionary *)change context:(void *)context {
    if (object == self.playerItem && [keyPath isEqualToString:@"status"]) {
        
        AVPlayerStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
        
        if (status == AVPlayerStatusReadyToPlay)
            self.musicView.play.enabled = YES;
        self.musicView.next.enabled = YES;
        self.musicView.last.enabled = YES;
        //只有在播放状态才能获取视频时间长度
        AVPlayerItem *playerItem = (AVPlayerItem *)object;
        
        NSTimeInterval duration = CMTimeGetSeconds(playerItem.asset.duration);
               self.videoDuration = duration;
        
        
        [self onButtonClick:self.musicView.play];
        
        
    }
    
    
    else if (self.song.status == AVPlayerStatusFailed) {
        // something went wrong. player.error should contain some information
        NSLog(@"not fineee");
        NSLog(@"%@",self.song.error);
        
    }
    else if (self.song.status == AVPlayerItemStatusUnknown) {
        NSLog(@"AVPlayer Unknown");
        
        
    }
}


-(void) onButtonClick:(id)sender{
    [self play:sender];
}
#pragma mark ** planDrag 进度条拖拽 单曲循环 顺序循环
- (void)planDrag
{
    
    if (self.musicView.play.selected == YES) {
        CMTime time = [self.song currentTime];
        time.value = self.musicView.plan.value * time.timescale;
        [self.song seekToTime:time];
        [self.song play];
    }
    else{
        CMTime time = [self.song currentTime];
        time.value = self.musicView.plan.value * time.timescale;
        [self.song seekToTime:time];
        [self.song pause];
        
    }
   
    
    
    
}
#pragma mark ** playCircle 照片旋转 进度条的左右时间
- (void)playCircle
{
    
    self.musicView.photobg.transform = CGAffineTransformRotate(self.musicView.photo.transform, M_PI_4 * 0.001);
     self.musicView.photo.transform = CGAffineTransformRotate(self.musicView.photo.transform, M_PI_4 * 0.001);
    if (self.song.currentTime.timescale == 0) {
    
    }
    else{
    self.currentTimeSec = (int)(self.song.currentTime.value / self.song.currentTime.timescale);

    int nowTime = self.currentTimeSec;
    NSLog(@"%d",nowTime);
    int minuteLeft = nowTime / 60;
    int secondLeft = nowTime % 60;  
    if (secondLeft < 10) {
        self.musicView.leftTime.text = [NSString stringWithFormat:@"%d:0%d",minuteLeft,secondLeft];
    }
    else
        self.musicView.leftTime.text = [NSString stringWithFormat:@"%d:%d",minuteLeft,secondLeft];
    int allTime = (int)self.videoDuration;
    int minuteRight = allTime / 60;
    int secondRight = allTime % 60;
    if (secondRight < 10) {
        self.musicView.rightTime.text = [NSString stringWithFormat:@"%d:0%d",minuteRight,secondRight];
    }
    else
        self.musicView.rightTime.text = [NSString stringWithFormat:@"%d:%d",minuteRight,secondRight];
    self.musicView.plan.maximumValue = allTime;
    [self.musicView.plan setValue:(float)nowTime animated:YES];
    if (nowTime == allTime) {
        [self.playerItem removeObserver:self forKeyPath:@"status"];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
        
        [self.timer invalidate];
        self.timer = nil;
        if (self.i == 99) {
            self.i = 0;
        }
        else{
            self.i++;
        }
        self.n = 0;
        [self musicViewSubViews];
        
    }
    }
    
}
#pragma mark ** 点赞功能 红心单曲循环 白心顺序循环
- (void)like:(UIButton *)button
{
    button.selected = !button.selected;
    if (button.selected == 0) {
        [self.musicView.like setImage:[UIImage imageNamed:@"likeOff.png"] forState:UIControlStateNormal];
        self.count--;
        NSLog(@"%ld",self.count);
    }
    else
    {
        [self.musicView.like setImage:[UIImage imageNamed:@"likeOn.png"] forState:UIControlStateNormal];
        self.count++;
        NSLog(@"%ld",self.count);
    }
}
#pragma mark ** start/stop 播放暂停功能
- (void)play:(UIButton *)button
{
    NSLog(@"%d",button.selected);
    button.selected = !button.selected;
    
    if (button.selected == 0) {
        [self.musicView.play setImage:[UIImage imageNamed:@"start.png"] forState:UIControlStateNormal];
        [self.timer invalidate];
        self.timer = nil;
        [self.song pause];
    }
    else
    {
        [self.musicView.play setImage:[UIImage imageNamed:@"stop.png"] forState:UIControlStateSelected];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(playCircle) userInfo:nil repeats:YES];
        [self.song play];
    }
    
}

#pragma mark ** 上一曲功能
- (void)last:(UIButton *)button
{
    if (self.i != 0) {
        self.i = self.i - 1;
        [self.song pause];
        
        [self.playerItem removeObserver:self forKeyPath:@"status"];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
        [self.timer invalidate];
        self.timer = nil;
        self.n = 0;
        [self musicViewSubViews];
        
    }
    else
    {
        self.i = self.songList.count - 1;
    }
    
}

#pragma mark ** 下一曲功能
- (void)next:(UIButton *)button
{
    if (self.i != self.songList.count - 1)
    {
        
        self.i = self.i + 1;
        [self.song pause];
        [self.playerItem removeObserver:self forKeyPath:@"status"];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
        [self.timer invalidate];
        self.timer = nil;
        self.n = 0;
        [self musicViewSubViews];
        
    }
    
    else
    {
        
        self.i = 0;
        
    }
    
}
#pragma mark ** 返回上一页
- (void)swip2:(UISwipeGestureRecognizer *)swip
{
    
    [self.song pause];
    [self.playerItem removeObserver:self forKeyPath:@"status"];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
    [self.timer invalidate];
    self.timer = nil;
    self.n = 0;
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)back
{
    
    [self.song pause];
    [self.playerItem removeObserver:self forKeyPath:@"status"];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
    [self.timer invalidate];
    self.timer = nil;
    self.n = 0;
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
